/*
 * @Author: 黄宇/Hyuishine
 * @Date: 2021-12-06 14:07:57
 * @LastEditors: 徐伟杰
 * @LastEditTime: 2022-12-01 16:49:38
 * @Description:
 * @Email: hyuishine@gmail.com
 * @Company: 3xData
 * @youWant: add you want
 */
import {
  login_login,
  get_userInfo,
  addOrganization,
  addUnitInfo,
  logOut,
  creditCode,
  getTree,
  getUserTicketApi,
} from "@/api/login.js";

import { baseApiUrl } from "@/config.js";

const login = {
  state: {
    notiaCount: 0, // 通知数量
    timer: null, // 定时任务
    userInfo: uni.getStorageSync("app_userInfo"), // 用户信息 会读取本地缓存 字段详情见储存用户信息

    token: "", // 用户token
    //! websocket
    WS: {
      vm: null, // websocket 实例
      status: false, // websocket 连接状态
      url: "", // websocket后台链接
      reconnectedTimes: 0, // websocket 已重连次数
      reconnectedRate: 5000, // 重连时间间隔 频率，单位毫秒
      maxTimes: 5, // websocket 最大重连尝试次数
      messageCounnt: 0, // 通过websocket 获取到的消息数量
    },
    form: {
      image: null, // 人像采集
      positivePhoto: null, // 身份证人像面
      backPhoto: null, // 身份证国徽面
      portraitCollection: null, // 人像采集
    },

    treeList: [], // 区域树

    reportId: "",
    sign: null,
    remark: uni.getStorageSync("authorloginIp") || null, // 当remark有值时代表修改过密码，若为空值时代表未修改过密码
    staffId: uni.getStorageSync("staffId") || null, // 员工id
    authorityList: uni.getStorageSync("authorityList"), // 用户权限
  },
  mutations: {
    // 缓存reportId
    set_reportId(state, data) {
      state.reportId = data;
    },
    // 缓存sign
    set_sign(state, data) {
      state.sign = data;
    },
    set_authority(state, data) {
      state.authorityList = data;
    },
    // 储存用户信息
    set_userInfo(state, [userInfo, token]) {
      const info = {
        tokenTime: new Date().getTime(),
        token: token || "", // 用户token
        userId: userInfo.userId || "", // 用户id
        userType: userInfo.userType || "", // 用户类型
        userCode: userInfo.userCode || "", // 用户编码
        status: userInfo.status || "", //
        sex: userInfo.sex || "", // 性别
        nickName: userInfo.userName || "", // 中文名/昵称
        avatar: userInfo.avatar || "", // 头像
        enterpriseId: userInfo.enterpriseId || "", // 公司id
        depId: userInfo.depId || "", // 部门id
        postId: userInfo.postId || "", //
        roles: userInfo.roles || [], // 有哪些角色
      };
      state.userInfo = info;
      uni.setStorageSync("app_userInfo", info);
    },
    get_userInfos(state) {
      return state.userInfo;
    },
    set_staffId(state, data) {
      state.staffId = data;
      uni.setStorageSync("staffId", data);
    },

    // todo 待适配
    // 初始化websocket
    WS_init(state) {
      state.WS.url =
        "ws://" +
        baseApiUrl.split("//")[1] +
        "/dunHandler?userId=" +
        state.userInfo.id;

      state.WS.vm = uni.connectSocket({
        url: state.WS.url,
        success() {
          console.log("连接成功");
          state.WS.status = true;
        },
        fail(err) {
          console.log("连接失败", err);
        },
      });

      // 启动websocket
      state.WS.vm.onOpen(() => {
        console.log("连接打开");
      });

      // 监听websocket 连接意外断开事件
      state.WS.vm.onError((err) => {
        console.log("已断开", err);

        reconnect();
      });

      // 监听websocket 后端传输数据
      state.WS.vm.onMessage((res) => {
        console.log("收到数据", res);
        state.WS.messageCounnt = JSON.parse(res.data).count;
      });

      // 重新连接websocket,在允许的最大重连次数中可以继续重连
      function reconnect() {
        if (state.WS.reconnectedTimes >= this.WS_maxTimes) {
          this.closeWS();
        } else {
          state.WS.reconnectedTimes++;
          let timer = setTimeout(() => {
            clearTimeout(timer);
          }, state.WS.reconnectedRate);
        }
      }
    },

    // 登陆失败时退出登录 清空用户数据
    // 因为是退出登录，所以不管这个接口有没有调通都应该清除用户信息
    loginErr_logout(state) {
      logOut((res) => {
        uni.removeStorageSync("app_userInfo");
        uni.removeStorageSync("authorityList");
        uni.removeStorageSync("authorloginIp");
        state.remark = null;
        state.userInfo = {};
        uni.reLaunch({
          url: "/pages/login/index",
        });
      });
    },

    set_loginIp(state, data) {
      state.remark = data;
      uni.setStorageSync("authorloginIp", data);
    },

    //! 拍照后将线上路径缓存至本地
    SETPHOTOCATCH(state, data) {
      state.form[data.key] = data.url;
    },
  },
  actions: {
    // 登录接口方法
    login_login({ commit }, obj) {
      return new Promise((resolve, reject) => {
        login_login(obj, function (data) {
          if (data.code === 200) {
            // 获取用户信息
            get_userInfo((res) => {
              if (res && res.code === 200) {
                // 储存用户信息
                commit("set_userInfo", [res.data, data.token]);
                uni.setStorageSync("authorityList", res.permissions);
                commit("set_authority", res.permissions);
                commit("set_loginIp", res.data?.sysUser?.remark || null);
                if (res.staffId) {
                  commit("set_staffId", res.staffId);
                }
                uni.setStorageSync("authorloginIp", res.data?.sysUser?.remark);
                //! 启动websocket
                // commit('WS_init')
                resolve(res);
              } else {
                commit("loginErr_logout");
                reject();
              }
            }, data.token);
          }
          resolve(data);
        });
      });
    },
    addOrganization({ commit }, obj) {
      return new Promise((resolve, reject) => {
        addOrganization(obj, function (data) {
          resolve(data);
        });
      });
    },
    // 服务机构注册时判断统一信用代码和单位名称
    getCreditCode({ commit }, obj) {
      return new Promise((resolve, reject) => {
        creditCode(obj, function (data) {
          resolve(data);
        });
      });
    },

    addUnitInfo({ commit }, obj) {
      return new Promise((resolve, reject) => {
        addUnitInfo(obj, function (data) {
          resolve(data);
        });
      });
    },
    getTreeList({ commit }, obj) {
      return new Promise((resolve, reject) => {
        getTree(obj, function ({ data }) {
          resolve(data);
        });
      });
    },

    getUserTicket({ commit }, obj) {
      return new Promise((resolve, reject) => {
        getUserTicketApi(obj, function (data) {
          resolve(data);
        });
      });
    },
  },
};

export default login;
